package cn.ljy.uem.web.interceptor.frontend.mobile;

import cn.ljy.authority.config.security.TokenUtil;
import cn.ljy.authority.model.SysUser;
import cn.ljy.authority.service.SysUserTokenFrontendService;
import cn.ljy.common.model.result.ResponseData;
import cn.ljy.common.model.result.ResultCode;
import cn.ljy.common.utils.ResponseUtil;
import cn.ljy.uem.model.SchoolStudent;
import cn.ljy.uem.service.common.CommonSchoolService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 学生模块的登录拦截器
 */
public class LoginForSchoolStudentInterceptor implements HandlerInterceptor {

    @Autowired
    private SysUserTokenFrontendService sysUserTokenFrontendService;
    @Autowired
    private CommonSchoolService commonSchoolService;

    //private static final String[] IGNORE_URI = {};//定义不拦截的资源

    /**
     * 在请求处理之前进行调用（Controller方法调用之前）
     * 基于URL实现的拦截器
     * 在执行action里面的处理逻辑之前执行，它返回的是boolean，这里如果我们返回true在接着执行postHandle和afterCompletion，如果我们返回false则中断执行。
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURL().toString();//获取被读取的接口路径,如http://127.0.0.1:8088/ebuy_springboot/backstage/logout
        boolean flag = false;//默认验证失败，即拦截请求
        String path = request.getServletPath();
        String token= TokenUtil.getAppToken();//读取前台token的值
        if(StringUtils.hasLength(token)){
            try {
                //验证token是否有效，如果有效则刷新token。
                //不需要，由token过滤器决定
//                sysUserTokenFrontendService.verifyAndRefreshUserToken(token);
                //获取登录账户信息
                SysUser user=sysUserTokenFrontendService.getUserFromToken(token);
                //获取登录账户对应的学生信息
                SchoolStudent student=commonSchoolService.getStudent(user);
                if(student!=null){
                    flag=true;
                }else{
                    ResponseUtil.responseJson(response, ResponseData.error(ResultCode.FORBIDDEN.getCode(),"操作失败：只有学生才能访问"));
                }
            } catch (Exception e) {
                //异常捕获器无法捕获这里的错误信息，要手动抓取并返回错误信息
                ResponseUtil.responseJson(response, ResponseData.error(ResultCode.UNAUTHORIZED.getCode(),e.getMessage()));
            }
        }else{
            ResponseUtil.responseJson(response, ResponseData.error(ResultCode.UNAUTHORIZED.getCode(),"请先登录"));
        }
        return flag;
    }
}
